package com.yingdong.sceneserver.inner.message;

import java.io.UnsupportedEncodingException;

import com.yingdong.sceneserver.opcode.Dispatcher;

import io.netty.buffer.ByteBuf;

public abstract class Message {

	public static final int INIT_SIZE = 0x40;

	protected ByteBuf buffer;


	public final ByteBuf getBuffer() {
		return buffer;
	}

	public static final void sendToClient(ByteBuf buffer, int sessionId) {
		sendToClientBySessionId(buffer, sessionId);
	}

	public static void sendToClientBySessionId(ByteBuf buffer, int sessionId) {
		int len = buffer.readableBytes();
		buffer.setInt(0,len + 4);
		buffer.setInt(4,len);
		buffer.writeInt(sessionId);
		Dispatcher.sceneServerSession.writeAndFlush(buffer);
	}

	public static String readString(ByteBuf buffer)  {
		int utflen = buffer.readUnsignedShort();
		if (utflen > 0) {
			byte[] byteArr = new byte[utflen];
		

			buffer.readBytes(byteArr, 0, utflen);


			try {
				return new String(byteArr,"utf8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				throw new RuntimeException("encoded wrong");
			}
		}

		return "";
	}

	public static void writeString(ByteBuf buf, String str) {
		try {
			byte[] bytes=str.getBytes("utf8");
			int len=bytes.length;
			buf.writeShort(len);
			buf.writeBytes(bytes);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("encoded wrong");
		}

	}

}
